<template>
	<view class="app">
		<uni-popup ref="showcoupon" :type="type">
			<scroll-view scroll-y="true" class="coupon-list" @touchmove.stop>
				<user-coupon-item :coupon="item" action-text="立即使用" @eventClick="selectCoupon(item)"
					v-for="item in coupons"></user-coupon-item>
			</scroll-view>
		</uni-popup>
		<!-- 金额明细 -->
		<view class="yt-list">
			<view class="yt-list-cell b-b">
				<text class="cell-tit clamp">交易价格</text>
				<text class="cell-tip active" >￥{{transactionAmount.toFixed(2)}}</text>
			</view>
			<view class="yt-list-cell b-b">
				<view class="cell-icon">
					券
				</view>
				<text class="cell-tit clamp">优惠券</text>
				<text class="cell-tip" v-if="coupons.length==0">
					<text>无可用优惠券</text>
				</text>
				<text class="cell-tip active" v-if="coupons.length>0" @click="togglePopup('bottom', 'coupon')">
					<text v-if="!selectedCoupon.userCouponUuid">{{coupons.length}}张优惠券可用</text>
					<text class="coupon-name" v-if="selectedCoupon.userCouponUuid">
						{{selectedCoupon.couponDTO.name}}
					</text>
					<text class="deduct-amount" v-if="selectedCoupon.userCouponUuid">
						{{deductAmount}}
					</text>
				</text>
				<uni-icons class="close" type="clear" color="#909399" size="20" @click="clearSelectedCoupon"
					v-if="selectedCoupon.userCouponUuid"></uni-icons>
			</view>
			<view class="yt-list-cell b-b">
				<text class="cell-tit clamp">实付金额</text>
				<text class="cell-tip active">￥{{actualAmount}}</text>
			</view>
		</view>
<!-- 		<view class="price-box">
			<text>支付金额</text>
			<text class="price">{{resourceTran.transactionAmount}}</text>
		</view> -->

		<view class="pay-type-list">
			<view class="type-item b-b" @click="changePayType(1)">
				<text class="iconfont icon-pay-wechat"></text>
				<view class="con">
					<text class="tit">微信支付</text>
					<text>推荐使用微信支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#26A69A" activeBorderColor="#26A69A" :checked='payType == 1' />
					</radio>
				</label>
			</view>
			<!-- #ifndef MP-WEIXIN -->
			<view class="type-item b-b" @click="changePayType(2)">
				<text class="iconfont icon-pay-alipay"></text>
				<view class="con">
					<text class="tit">支付宝支付</text>
				</view>
				<label class="radio">
					<radio value="" color="#26A69A" activeBorderColor="#26A69A" :checked='payType == 2' />
					</radio>
				</label>
			</view>
			<!-- #endif -->
			<view class="type-item" @click="changePayType(3)">
				<text class="iconfont icon-pay-balance"></text>
				<view class="con">
					<text class="tit">余额支付</text>
					<text>可用余额 ¥{{userInfo.availableBalance}}</text>
				</view>
				<label class="radio">
					<radio value="" color="#26A69A" activeBorderColor="#26A69A" :checked='payType == 3' />
					</radio>
				</label>
			</view>
		</view>
		<view class="privacy">
			<view>1. 您将购买的商品为虚拟内容服务, 购买后不支持退订、转让、退还、请斟酌确认。</view>
			<view>2. 产品有效期以对应商品详情页中标注的期限为准。您理解并同意，平台方可以出于商业考量及自身经营计划，单方修改、调整有效期限及收费标准，前述期限及标准修改、变更或执行前，平台将在相应服务页面进行通知或公告</view>
			<view>3. 内容购买后可在[我的]-[已购资源]中查看和使用，如有问题请在[我的]-[客服中心]咨询</view>
			<view>4. 平台拥有对产品及相关条款的最终解释权</view>
		</view>
		<!-- #ifdef MP-WEIXIN -->
		<view class="button-base" @click="confirmWx">确认支付({{actualAmount}}元)</view>
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
		<view class="button-base" @click="confirm">确认支付({{actualAmount}}元)</view>
		<!-- #endif -->
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import uniPopup from "@/components/uni-popup/uni-popup.vue"
	import userCouponItem from "@/components/user-coupon-item.vue"
	// #ifdef H5
	const wx = require('weixin-js-sdk');
	// #endif
	export default {
		data() {
			return {
				payType: 1,
				tranCode: '',
				resourceTran: {},
				suscribeMsgList: [],
				coupons: [], //有效优惠券
				selectedCoupon: {}, //选择使用的优惠券
				maskState: 0 ,//优惠券面板显示状态
				transactionAmount: 0.00, //资源价格
				deductAmount: 0.00, //优惠金额
				actualAmount: 0.00, //实付金额
				type: ''
			};
		},
		components: {
			uniPopup,
			userCouponItem
		},
		computed: {
			...mapState(['hasLogin', 'userInfo', 'footPrint', 'applicationConfig'])
		},
		onLoad(options) {
			this.tranCode = options.tranCode;
			this.inquiryResourceTran(this.tranCode);
			this.inquirySuscribeMsg();
			this.searchCoupon();
		},

		methods: {
			togglePopup(type, open) {
				this.type = type
				this.$nextTick(() => {
					this.$refs['show' + open].open()
				})
			},
			//获取扣减最多的优惠券
			getBestCoupon(resourceDTO) {
				let postData = {
					userDTO:{
						userUuid:this.userInfo.userUuid
					},
					resourceDTO:{
						resourceUuid: resourceDTO.resourceUuid
					}
				};
				this.$api.request.bestCoupon(postData, res => {
					if (res.body.status.statusCode === '0') {
						var selectedCoupon = res.body.data;
						if(selectedCoupon){
							this.selectCoupon(selectedCoupon)
						}
					}
				}, true);
			},
			//搜索可用优惠券
			searchCoupon() {
				var keyArray = ['USER', 'IS_EXPIRED', 'IS_USED', 'IS_STARTED'];
				let postData = {
					keyArray: keyArray,
					userUuid: this.userInfo.userUuid,
					expired: false,
					used: false,
					started: true,
					startIndex: 0,
					pageSize: 50 //默认查询50张有效优惠券, 用户大于50张则多余部分不会显示
				};
				//加载中
				this.$api.request.userCoupon(postData, res => {
					if (res.body.status.statusCode === '0') {
						var coupons = res.body.data.userCoupons;
						this.coupons = coupons;
					}
				}, true);
			},
			// 不使用优惠券
			clearSelectedCoupon() {
				this.selectedCoupon = {};
				this.selectCoupon(this.selectedCoupon);
			},
			// 选中优惠券
			selectCoupon(item) {
				//计算当前商品使用优惠券后的优惠金额
				let postData = {
					transactionCode: this.tranCode,
					userCouponDTO: {
						userCouponUuid: item.userCouponUuid
					}
				}
				this.$api.request.calculateCouponAmount(postData, res => {
					if (res.body.status.statusCode === '0') {
						this.deductAmount = res.body.data.deductAmount;
						this.actualAmount = (this.transactionAmount - this.deductAmount).toFixed(2);
						this.selectedCoupon = item;
						this.$refs.showcoupon.close();
					} else {
						this.$api.msg(res.body.status.errorDesc);
					}
				}, false);
			},
			//选择支付方式
			changePayType(type) {
				this.payType = type;
			},
			//确认支付
			confirmWx: function() {
				uni.requestSubscribeMessage({
					// 订单模板消息
					tmplIds: this.suscribeMsgList,
					success: function(res) {
						console.log('订单模板消息订阅成功');
					}
				});
				if (this.payType === 1) {
					this.wechatPay();
				} else if (this.payType === 2) {
					this.alipayPay();
				} else if (this.payType === 3) {
					this.balancePay();
				}

			},
			//确认支付
			confirm: function() {
				if (this.payType === 1) {
					this.wechatPay();
				} else if (this.payType === 2) {
					this.alipayPay();
				} else if (this.payType === 3) {
					this.balancePay();
				}

			},
			wechatPay() {
				// #ifdef H5
				this.wechatPayH5();
				// #endif

				// #ifdef APP-PLUS
				this.wechatPayApp();
				// #endif

				// #ifdef MP-WEIXIN
				this.wechatPayMP();
				// #endif
			},
			wechatPayApp() {
				let that = this;
				var options = {
					transactionCode: that.tranCode
				};
				that.$api.request.resourceWechatPayApp(options, res => {
					if (res.body.status.statusCode == 0) {
						var data = res.body.data;
						this.invokeWechatPayApp(data); //客户端调起微信支付
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			wechatPayH5() {
				let that = this;
				var options = {
					transactionCode: that.tranCode,
					openId: this.userInfo.openId
				};
				that.$api.request.resourceWechatPayH5(options, res => {
					if (res.body.status.statusCode == 0) {
						var data = res.body.data;
						this.invokeWechatPayH5(data); //客户端调起微信支付
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			invokeWechatPayH5(order) {
				let that = this;
				var options = {
					url: document.URL
				};
				that.$api.request.getSignature(options, res => {
					if (res.body.status.statusCode == 0) {
						var jsSignature = res.body.data;
						wx.config({
							debug: false,
							appId: jsSignature.appId,
							timestamp: jsSignature.timestamp,
							nonceStr: jsSignature.nonceStr,
							signature: jsSignature.signature,
							jsApiList: ['chooseWXPay']
						})
						wx.ready(function() {
							wx.chooseWXPay({
								timestamp: order
									.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
								nonceStr: order.nonceStr, // 支付签名随机串，不长于 32 位
								package: order
									.packageStr, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
								signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
								paySign: order.signature, // 支付签名
								success: function(res) {
									uni.redirectTo({
										url: '/pages/resource/pay-resource-success'
									})
								}
							});
						})
					}
				});
			},
			invokeWechatPayApp(order) {
				uni.requestPayment({
					provider: 'wxpay', //微信支付
					orderInfo: {
						"appid": order.appId,
						"noncestr": order.nonceStr,
						"package": order.packageStr,
						"partnerid": order.partnerId,
						"prepayid": order.prepayId,
						"timestamp": order.timestamp,
						"sign": order.signature
					},
					success: function(res) {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/resource/pay-resource-success'
							});
						}, 1000);
					},
					fail: function(err) {
						setTimeout(() => {
							uni.redirectTo({
								url: '/pages/order/order'
							});
						}, 1000);
					},
				})
			},
			wechatPayMP() {
				//微信小程序支付
				let that = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						console.log(loginRes.code);
						that.$api.request.resourceWechatPay({
							transactionCode: that.tranCode,
							code: loginRes.code
						}, res => {
							if (res.body.status.statusCode === '0') {
								var data = res.body.data;
								console.log(res.body.data);
								uni.requestPayment({
									provider: 'wxpay',
									timeStamp: data.timestamp,
									nonceStr: data.nonceStr,
									package: data.packageStr,
									signType: 'MD5',
									paySign: data.signature,
									success: function(res) {
										uni.redirectTo({
											url: '/pages/resource/pay-resource-success'
										})
									},
									fail: function(err) {
										console.log('fail:' + JSON.stringify(err));
									}
								});
							} else {
								console.log(res.body.status.errorDesc);
							}
						});
					}
				});
			},
			//支付宝支付
			alipayPay() {
				// #ifdef H5
				this.alipayH5();
				// #endif

				// #ifdef APP-PLUS
				this.alipayApp();
				// #endif
			},
			//支付宝在H5中支付
			alipayH5() {
				this.$api.request.resourceAlipay({
					transactionCode: this.tranCode,
					paymentMethod: this.payType
				}, res => {
					if (res.body.status.statusCode === '0') {
						let alipayForm = res.body.data.alipayForm;
						let div = document.createElement('div'); // 创建div
						div.innerHTML = alipayForm; // 将返回的form 放入div
						document.body.appendChild(div);
						document.forms[0].acceptCharset = 'UTF-8'
						document.forms[0].submit();
					} else {
						this.$api.msg(res.body.status.errorDesc);
					}
				});
			},
			//支付宝在APP中支付
			alipayApp() {
				this.$api.request.resourceAlipayApp({
					transactionCode: this.tranCode
				}, res => {
					if (res.body.status.statusCode === '0') {
						let alipayForm = res.body.data.alipayForm;
						alert(alipayForm);
						uni.requestPayment({
							provider: 'alipay', //支付宝支付
							orderInfo: alipayForm,
							success: function(res) {
								alert('success');
								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/resource/pay-resource-success'
									});
								}, 1000);
							},
							fail: function(err) {
								alert('fail');
								setTimeout(() => {
									uni.redirectTo({
										url: '/pages/order/order'
									});
								}, 1000);
							},
						})
					} else {
						this.$api.msg(res.body.status.errorDesc);
					}
				});
			},
			//余额支付
			balancePay() {
				this.$api.request.resourceBalancePay({
					transactionCode: this.tranCode,
					paymentMethod: this.payType
				}, res => {
					if (res.body.status.statusCode === '0') {
						uni.redirectTo({
							url: '/pages/resource/pay-resource-success'
						})
					} else {
						this.$api.msg(res.body.status.errorDesc);
					}
				});
			},
			//查询资源购买详情
			inquiryResourceTran(tranCode) {
				this.$api.request.inquiryResourceTran({
					transactionCode: tranCode
				}, res => {
					if (res.body.status.statusCode === '0') {
						this.resourceTran = res.body.data;
						this.transactionAmount = this.resourceTran.transactionAmount;
						this.actualAmount = (this.transactionAmount - this.deductAmount).toFixed(2);
						//自动选择最优惠的券
						this.getBestCoupon(this.resourceTran.resourceDTO);
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			},
			//查询订阅消息
			inquirySuscribeMsg() {
				this.$api.request.wxSuscribeMsg({}, res => {
					if (res.body.status.statusCode === '0') {
						this.suscribeMsgList = res.body.data.suscribeMsgList;
					} else {
						console.log(res.body.status.errorDesc);
					}
				});
			}

		}
	}
</script>

<style lang='scss'>
	page {
		background: $bg-color-light;
	}

	.app {
		margin: 0 $page-row-spacing;
	}

	.yt-list {
		margin-top: 16upx;
		background: #fff;
	}

	.yt-list-cell {
		display: flex;
		align-items: center;
		padding: 10upx 30upx 10upx 40upx;
		line-height: 70upx;
		position: relative;

		&.cell-hover {
			background: #fafafa;
		}

		&.b-b:after {
			left: 30upx;
		}

		.cell-icon {
			height: 32upx;
			width: 32upx;
			font-size: 22upx;
			color: #fff;
			text-align: center;
			line-height: 32upx;
			background: #f85e52;
			border-radius: 4upx;
			margin-right: 12upx;

			&.hb {
				background: #ffaa0e;
			}

			&.lpk {
				background: #3ab54a;
			}

		}

		.cell-more {
			align-self: center;
			font-size: 24upx;
			color: $font-color-light;
			margin-left: 8upx;
			margin-right: -10upx;
		}

		.cell-tit {
			flex: 1;
			font-size: 26upx;
			color: $font-color-light;
			margin-right: 10upx;
		}

		.cell-tip {
			font-size: 26upx;
			color: $font-color-light;

			.coupon-name {
				background: $uni-color-primary;
				color: #fff;
				padding: 6upx;
			}

			.deduct-amount {
				margin-left: 20upx;

				&::before {
					content: '-￥';
				}
			}

			&.disabled {
				color: $font-color-light;
			}

			&.active {
				color: $font-color-dark;
			}

			&.red {
				color: $base-color;
			}

			& .close {
				color: $font-color-light;
				margin-left: 20upx;
			}
		}

		&.desc-cell {
			.cell-tit {
				max-width: 90upx;
			}
		}

		.desc {
			flex: 1;
			font-size: $font-base;
			color: $font-color-dark;
		}
	}
	
	.coupon-list{
		max-height: 400px;
	}

	.price-box {
		height: 265upx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 28upx;
		color: $font-color-light;

		.price {
			font-size: 50upx;
			color: $font-color-dark;
			font-weight: bold;
			margin-top: 12upx;

			&:before {
				content: '￥';
				font-size: 40upx;
			}
		}
	}

	.pay-type-list {
		margin-top: 20upx;
		/* background-color: #fff; */
		padding-left: 60upx;

		.type-item {
			height: 120upx;
			padding: 20upx 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding-right: 60upx;
			font-size: 30upx;
			position: relative;
		}

		.iconfont {
			width: 100upx;
			font-size: 52upx;
		}

		.icon-pay-balance {
			color: #fe8e2e;
		}

		.icon-pay-wechat {
			color: #36cb59;
		}

		.icon-pay-alipay {
			color: #01aaef;
		}

		.tit {
			font-size: $font-lg;
			color: $font-color-dark;
			margin-bottom: 4upx;
		}

		.con {
			flex: 1;
			display: flex;
			flex-direction: column;
			font-size: $font-sm;
			color: $font-color-light;
		}
	}
	.privacy {
		margin: 40upx 0 ;
		font-size: $font-base;
		color: $font-color-light;
		line-height: 50upx;
	
		.link {
			color: $base-color;
			text-decoration: none;
		}
	}
</style>